window.DocumentList = {
    element:null,
    _baseUrl:'http://localhost:8888/',
    _getDataUrl:'w/file/getFileList',
    _createFolderUrl:'w/file/createFolder',
    _deleteToTrashUrl:'w/file/deleteToTrash',
    _renameFolderUrl:'w/file/renameFolder',
    _uploadFileUrl:'w/file/uploadFiles',
    /*当前页面的历史路径*/
    _pathIndexList:[
        /*根目录*/
        {
            'fileId':0,
            'fileName':'全部文件'
        },
    ],
    _chooseFileList:[],
    _createFolder:function () {
        parent.layer.prompt({
            title:"请输入文件名",
            formType:0,
            value:"新建文件夹",
            zIndex:99999999999
        }, function (value, index) {
            parent.layer.close(index);
            //取_pathIndexList最后一个的Index进行查询
            var _pathIndexListLength=DocumentList._pathIndexList.length;
            var _parentIndexList="";
            for(var i=0;i<_pathIndexListLength;i++){
                _parentIndexList+=DocumentList._pathIndexList[i].fileId+",";
            }
            _parentIndexList=_parentIndexList.substring(0,_parentIndexList.length-1);
            var _nowFile=DocumentList._pathIndexList[_pathIndexListLength-1];
            var _nowIndex=_nowFile.fileId;
            DocumentList._ajaxPost(
                DocumentList._baseUrl+DocumentList._createFolderUrl,
                {
                    'parentIndexList':_parentIndexList,
                    'thisIndex': _nowIndex,
                    'folderName': value
                },
                function (result) {
                    if(result.status === "success"){
                        //刷新页面
                        DocumentList._renderThisPage();
                    } else {//新建文件夹失败不用刷新当前页面
                        parent.layer.alert(result.message);
                    }
                },
                true
            );
        });
    },
    _deleteToTrash:function(){
        if(DocumentList._chooseFileList.length > 0){
            parent.layer.confirm('是否确定移入到回收站？',{icon: 3, title:'是否删除'},function(index){
                DocumentList._ajaxPost(
                    DocumentList._baseUrl+DocumentList._deleteToTrashUrl,
                    {
                        'thisIndexs': DocumentList._chooseFileList,
                    },
                    function (result) {
                        if(result.status === "success"){
                            DocumentList._renderThisPage();
                        } else {
                            parent.layer.alert(result.message);
                        }
                    },
                    true
                );
                parent.layer.close(index);
            });
        }else{
            parent.layer.alert("请至少选中一个文件进行删除操作！");
        }
    },
    _renameFile:function(){
        if(DocumentList._chooseFileList.length === 1){
            var chooseFile=DocumentList._chooseFileList[0];
            var fileName="";
            $("#folderViewList .checked").each(function () {
                var $this=$(this);
                if(parseInt($this.data("index")) === chooseFile){
                    fileName=$this.find(".file-name").html();
                }
            });
            parent.layer.prompt({
                title:"请重新输入文件名",
                formType:0,
                value:fileName,
                zIndex:99999999999
            }, function (value,index) {
                parent.layer.close(index);
                //取_pathIndexList最后一个的Index进行查询
                DocumentList._ajaxPost(
                    DocumentList._baseUrl+DocumentList._renameFolderUrl,
                    {
                        'thisIndex': chooseFile,
                        'folderName': value
                    },
                    function (result) {
                        if(result.status === "success"){
                            //刷新页面
                            DocumentList._renderThisPage();
                        } else {//新建文件夹失败不用刷新当前页面
                            parent.layer.alert(result.message);
                        }
                    },
                    true
                );
            });
        }else{
            parent.layer.alert("请选中一个文件进行重命名操作！");
        }
    },
    _openChooseFileWin:function () {
        //打开选择文件的窗口
        $("#upload-input").click();
    },
    _uploadFile:function () {
        var files=new FormData($("#fileList")[0]);
        var _pathIndexListLength=DocumentList._pathIndexList.length;
        var _parentIndexList="";
        for(var i=0;i<_pathIndexListLength;i++){
            _parentIndexList+=DocumentList._pathIndexList[i].fileId+",";
        }
        _parentIndexList=_parentIndexList.substring(0,_parentIndexList.length-1);
        var _nowFile=DocumentList._pathIndexList[_pathIndexListLength-1];
        var _nowIndex=_nowFile.fileId;
        files.set('parentIndexList',_parentIndexList);
        files.set('thisIndex',_nowIndex);
        var index=null;
        $.ajax({
            url: DocumentList._baseUrl+DocumentList._uploadFileUrl,
            type: 'POST',
            data: files,
            cache: false,
            processData: false,
            contentType: false,
            beforeSend: function(){
                index = parent.layer.load(2, {time: 10*1000});
            },
            success : function(result) {
                parent.layer.close(index);
                if (JSON.parse(result).status === "success") {
                    DocumentList._renderThisPage();
                } else {
                    parent.layer.alert(JSON.parse(result).message);
                }
            }
        });
    },
    /*执行刷新方法之前一定要修改_pathIndexList*/
    _renderThisPage:function () {//渲染页面
        //清空_chooseFileList数组
        DocumentList._chooseFileList.splice(0,DocumentList._chooseFileList.length);
        //取_pathIndexList最后一个的Index进行查询
        var _nowFile=DocumentList._pathIndexList[DocumentList._pathIndexList.length - 1];
        var _nowIndex=_nowFile.fileId;
        DocumentList._ajaxGet(
            DocumentList._baseUrl+DocumentList._getDataUrl,
            {'thisIndex': _nowIndex},
            function (result) {
                //首先要清空当前页
                DocumentList._emptyThisPage();
                if(result.status === "success"){
                    var data=result.data;
                    var $folderViewList=$("#folderViewList");
                    var _fileListLength=data.length;
                    var htmlData="";
                    for(var i=0;i<_fileListLength;i++){
                        var _file=data[i];
                        if(parseInt(_file.fileType) === 0){
                            htmlData+=
                                '<div data-index="'+ _file.fileId +'" class="file-box">\n' +
                                '    <div class="folder file">\n' +
                                '        <a href="javascript:void(0);">\n' +
                                '            <span class="corner">\n' +
                                '                <i class="fa fa-check-circle" aria-hidden="true"></i>\n' +
                                '            </span>\n' +
                                '            <div class="icon">\n' +
                                '                <i class="' + _file.fileIcon + '" aria-hidden="true"></i>\n' +
                                '            </div>\n' +
                                '            <div class="file-name" title="'+ _file.fileName +'">'+ _file.fileName +'</div>\n' +
                                '        </a>\n' +
                                '    </div>\n' +
                                '</div>';
                        }else{
                            htmlData+=
                                '<div data-index="'+ _file.fileId +'" class="file-box">\n' +
                                '    <div class="doc file">\n' +
                                '        <a href="javascript:void(0);">\n' +
                                '            <span class="corner">\n' +
                                '                <i class="fa fa-check-circle" aria-hidden="true"></i>\n' +
                                '            </span>\n' +
                                '            <div class="icon">\n' +
                                '                <i class="' + _file.fileIcon + '" aria-hidden="true"></i>\n' +
                                '            </div>\n' +
                                '            <div class="file-name" title="'+ _file.fileName +'">'+ _file.fileName +'</div>\n' +
                                '        </a>\n' +
                                '    </div>\n' +
                                '</div>';
                        }
                    }
                    //加载页面
                    $folderViewList.html(htmlData);
                    //刷新右键菜单
                    DocumentList._refreshContextMenu();
                } else {
                    console.log(result.message);
                    // parent.layer.alert(result.message);
                }
                //刷新历史路径
                DocumentList._renderHistoryPath();
                //刷新Url
                DocumentList._renderPageUrl();
            },
            true
        );
    },
    _emptyThisPage:function(){
        $("#folderViewList").empty();
    },
    _goBack:function(){
        if(DocumentList._pathIndexList.length > 1){
            //返回上一级
            DocumentList._pathIndexList.pop();
            DocumentList._renderThisPage();
        }
    },
    _renderHistoryPath:function(){
        //刷新路径的历史记录
        var $historyPath=$("#historyPath");
        var pathIndexListLength=DocumentList._pathIndexList.length;
        var htmlData="";
        for (var i=0;i<pathIndexListLength;i++){
            var pathIndex=DocumentList._pathIndexList[i];
            if(i === pathIndexListLength - 1){
                htmlData+=
                    '<a data-index="'+pathIndex.fileId+'" href="javascript:;">'+pathIndex.fileName+'</a>';
            }else{
                htmlData+=
                    '<a data-index="'+pathIndex.fileId+'" href="javascript:;" class="isClick">'+pathIndex.fileName+'</a>';
            }
        }
        //加载页面
        $historyPath.html(htmlData);
        if(DocumentList.element){
            DocumentList.element.init();
        }
    },
    _renderPageUrl:function(){
        var pathIndexListLength=DocumentList._pathIndexList.length;
        var currentPath="#";
        for (var i=0;i<pathIndexListLength;i++){
            var pathIndex=DocumentList._pathIndexList[i];
            currentPath+=pathIndex.fileId+'@';
        }
        var _index=parent.layer.getFrameIndex(window.name);
        var $iframe=parent.Win10.getLayeroByIndex(_index).find('iframe');
        var _originUrl=$iframe.attr('src');
        $iframe.attr('src',_originUrl.split('#')[0]+currentPath);
    },
    _setContextMenu:function (jq_dom, menu,isDoc) {
        if(typeof (jq_dom)==='string'){
            jq_dom=$(jq_dom);
        }
        jq_dom.unbind('contextmenu');
        jq_dom.on('contextmenu', function(event) {
            if(menu){
                DocumentList._renderContextMenu(event.clientX,event.clientY,menu,this,isDoc);
                if (event.cancelable) {
                    // 判断默认行为是否已经被禁用
                    if (!event.defaultPrevented) {
                        event.preventDefault();
                        //右键点击选中该文件>>参考百度网盘实现方式
                        var $this = $(this);
                        var $fileParent = $this.parent('.file-box');
                        var _fileIndex = $fileParent.data('index');
                        //检查元素
                        var _arrayIndex = $.inArray(parseInt(_fileIndex),DocumentList._chooseFileList);
                        if (_arrayIndex < 0){//第一次添加
                            if(_fileIndex){
                                //添加元素
                                DocumentList._chooseFileList.push(_fileIndex);
                                //修改样式
                                $fileParent.addClass('checked');
                            }
                        }
                    }
                }
                event.stopPropagation();
            }
        });
    },
    _renderContextMenu:function (x,y,menu,trigger,isDoc) {
        this._removeContextMenu();
        if(menu===true){return;}
        var dom;
        if(isDoc){
            dom = $("<div class='document-context-menu'><ul></ul></div>");
        }else{
            dom = $("<div class='folder-context-menu'><ul></ul></div>");
        }
        $('#folderList').append(dom);
        var ul=dom.find('ul');
        for(var i=0;i<menu.length;i++){
            var item=menu[i];
            if(item==='|'){
                ul.append($('<hr/>'));
                continue;
            }
            if(typeof(item)==='string'){
                ul.append($('<li>'+item+'</li>'));
                continue;
            }
            if(typeof(item)==='object'){
                var sub=$('<li>'+item[0]+'</li>');
                ul.append(sub);
                sub.click(trigger,item[1]);
                continue;
            }
        }
        //修正坐标
        if(x+150>document.body.clientWidth){x-=150}
        if(y+dom.height()>document.body.clientHeight){y-=dom.height()}
        dom.css({
            top:y,
            left:x,
        });
    },
    _removeContextMenu:function () {
        $('.document-context-menu').remove();
        $('.folder-context-menu').remove();
        //移除父元素的右键菜单
        parent.$('.win10-context-menu').remove();
    },
    _refreshContextMenu:function () {
        //设置默认右键菜单
        DocumentList._setContextMenu('#folderList',true,true);
        DocumentList._setContextMenu('#folderList>.layui-row',[
            ['<i class="fa fa-fw fa-window-maximize" aria-hidden="true"></i> '+'新建文件夹',function () {DocumentList._createFolder()}],
            ['<i class="fa fa-upload" aria-hidden="true"></i>  '+'上传文件',function () {DocumentList._openChooseFileWin()}],
            '|',
            ['<i class="fa fa-fw fa-info-circle" aria-hidden="true"></i> '+'按照文件名排序',function () {}],
            ['<i class="fa fa-fw fa-info-circle" aria-hidden="true"></i> '+'按照时间排序',function () {}],
        ],true);
        DocumentList._setContextMenu('#folderViewList .file',true,false);
        DocumentList._setContextMenu('#folderViewList .file',[
            ['<span class="folder-method">'+'打开'+'</span>',function () {}],
            ['<span class="folder-method">'+'下载'+'</span>',function () {}],
            '|',
            ['<span class="folder-method">'+'复制到'+'</span>',function () {}],
            ['<span class="folder-method">'+'移动到'+'</span>',function () {}],
            '|',
            ['<span class="folder-method">'+'重命名'+'</span>',function () {DocumentList._renameFile()}],
            ['<span class="folder-method">'+'删除'+'</span>',function () {DocumentList._deleteToTrash()}],
        ],false);
    },
    _init:function () {
        //首先渲染页面
        DocumentList._renderThisPage();
        //点击清空右键菜单
        $(document).click(function (event) {
            if(!event.button)
                DocumentList._removeContextMenu();
        });
        //禁用右键的右键
        $(document).on('contextmenu','.document-context-menu',function (e) {
            e.preventDefault();
            e.stopPropagation();
        });
        $(document).on('contextmenu','.folder-context-menu',function (e) {
            e.preventDefault();
            e.stopPropagation();
        });
        //选中文件方法
        $(document).on('click', '.file .corner', function (event) {
            var $this = $(this);
            var $fileParent = $this.parent().parent().parent('.file-box');
            var _fileIndex = $fileParent.data('index');
            //检查元素
            var _arrayIndex = $.inArray(parseInt(_fileIndex),DocumentList._chooseFileList);
            if (_arrayIndex >= 0){
                // 删除数组元素
                DocumentList._chooseFileList.splice($.inArray(parseInt(_fileIndex),DocumentList._chooseFileList), 1);
                //修改样式
                $fileParent.removeClass('checked');
            }else{
                if(_fileIndex){
                    //添加元素
                    DocumentList._chooseFileList.push(_fileIndex);
                    //修改样式
                    $fileParent.addClass('checked');
                }
            }
            event.stopPropagation();
        });
        //点击文件夹方法
        $(document).on('click', '#folderViewList .folder', function () {
            var $this = $(this);
            var _thisIndex = $this.parent(".file-box").data('index');
            var thisFileName = $this.find(".file-name");
            //添加到页面的历史路径中
            DocumentList._pathIndexList.push({
                'fileId':_thisIndex,
                'fileName':thisFileName.html()
            });
            //执行刷新方法
            DocumentList._renderThisPage();
        });
        //点击文件夹方法
        $(document).on('click', '#folderViewList .doc', function () {
            var $this = $(this);
            var _thisIndex = $this.parent(".file-box").data('index');
            //预览文件**
            parent.layer.confirm('是否确定预览当前文件？',{icon: 3, title:'是否预览'},function(index){
                console.log(_thisIndex);
                parent.layer.close(index);
            });
        });
        $(document).on('click', '#historyPath .isClick', function () {
            var $this = $(this);
            var _thisIndex = $this.data('index');
            var _pathIndexListLength=DocumentList._pathIndexList.length;
            var _inArrayIndex=-1;
            for(var i=0;i<_pathIndexListLength;i++){
                var fileId=DocumentList._pathIndexList[i].fileId;
                if(parseInt(_thisIndex) === parseInt(fileId)){
                    _inArrayIndex=i;
                    break
                }
            }
            DocumentList._pathIndexList.splice(_inArrayIndex+1, DocumentList._pathIndexList.length);
            DocumentList._renderThisPage();
        });

    },
    /*========================================================================*/
    /*下面是封装方法*/
    _ajaxRequest:function (type, url, data, callback, loading, cache) {
        var ajaxConfig = {
            url: '',
            data: {},
            callback: null,
            loading: true,
            cache: true,
            async: true
        };
        // 判断每一个参数url的类型
        // 如果是对象则是请求参数对象
        // 如果是字符串则是请求URL，参数和回调要继续检测后面的参数
        if (typeof url === 'string') {
            ajaxConfig.url = url;
            ajaxConfig.data = data;
            ajaxConfig.callback = callback;
            ajaxConfig.loading = typeof(loading) === 'undefined' ? true : loading;
            ajaxConfig.cache = cache;
        } else {
            ajaxConfig = $.extend({}, ajaxConfig, url);
        }
        var index = null;
        $.ajax({
            type: type,
            url: ajaxConfig.url,
            data: ajaxConfig.data,
            beforeSend: function() {
                if (ajaxConfig.loading) {
                    index = parent.layer.load(2, {time: 10*1000});
                }
            },
            dataType: 'json',
            cache: ajaxConfig.cache,
            async: ajaxConfig.async,
            traditional:true,
            success: function(result) {
                if (ajaxConfig.loading) {
                    parent.layer.close(index);
                }
                ajaxConfig.callback(result);
            },
            error: function(result) {
                if (ajaxConfig.loading) {
                    parent.layer.close(index);
                }
            }
        })
    },
    _ajaxGet:function (url, data, callback, loading) {
        DocumentList._ajaxRequest('GET', url, data, callback, loading, true);
    },
    _ajaxPost:function (url, data, callback, loading) {
        DocumentList._ajaxRequest('POST', url, data, callback, loading, false);
    }
};
$(function () {
    layui.use('element', function(){
        DocumentList.element = layui.element; //导航的hover效果、二级菜单等功能，需要依赖element模块
    });
    DocumentList._init();
});